<!--
# coding=UTF-8
# Copyright (c) 2025 Bird Software Solutions Ltd
# This program and the accompanying materials
# are made available under the terms of the Eclipse Public License 2.0
# which accompanies this distribution, and is available at
# https://www.eclipse.org/legal/epl-2.0/
#
# SPDX-License-Identifier: EPL-2.0
#
# Contributors:
#    Neil Mackenzie - initial API and implementation
#    Benjamin Arfa - improvements
#
-->
{% extends "pybirdai/workflow/base.html" %}

{% block workflow_content %}
<!-- Server Restart Overlay -->
<div id="server-restart-overlay" style="display: none;">
    <div class="overlay-content">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>
        <h3>Server is restarting...</h3>
        <p>Please wait while the database setup completes.</p>
        <p>The application will be available again shortly.</p>
        <p class="overlay-timer">Checking server status... <span id="overlay-timer-seconds">0</span>s</p>
    </div>
</div>

<h1>BIRD Data Processing Workflow</h1>

<!-- Configuration Section -->
{% include 'pybirdai/workflow/configuration_section.html' %}

<!-- Database Status Notice -->
{% if not database_ready %}
<div style="background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 15px; margin-bottom: 20px;">
    <h3 style="color: #d68910; margin-bottom: 10px;">⚠️ Database Not Available</h3>
    <p style="margin-bottom: 10px; color: #856404;">
        The BIRD database has not been created yet. To get started:
    </p>
    <ol style="color: #856404; margin-left: 20px;">
        <li>Configure your data sources above</li>
        <li>Click Retrieve Artifacts and Setup Database</li>
        <li>Once complete, the full workflow interface will be available</li>
    </ol>
</div>
{% endif %}

<!-- Progress Bar -->
<!-- <div class="progress-bar">
    <div class="progress-fill" style="width: {{ progress }}%;">
        {{ progress }}% Complete
    </div>
</div> -->



<!-- Task Grid -->
<div class="task-grid">


    <!--  -->
    <div class="task-card">
        <div id="reset-session-status" style="display: none; margin-top: 10px; padding: 10px; border-radius: 5px;"></div>
    </div>
    <div class="task-card">
        <h3>Do</h3>
    </div>
    <div class="task-card">
        <h3>Review</h3>
    </div>
 

    {% if database_ready and task_grid %}
        {% for task in task_grid %}
        <div class="task-card">
            <h3>{{ forloop.counter}}. {{ task.task_name }}</h3>
        </div>

        <div class="task-card">
            
            <a href="{% url 'pybirdai:workflow_task' task_number=task.task_number operation='do' %}"
               class="operation-btn {{ task.operations.do.status }}" >
                Do
            </a>
           
        </div>

        <div class="task-card">

            <a href="{% url 'pybirdai:workflow_task' task_number=task.task_number operation='review' %}"
               class="operation-btn {% if task.operations.do.status != 'pending' %} running {% else %} invalidated {% endif %}">
                Review
            </a>
  
        </div>

        
        {% endfor %}
    {% else %}
        <!-- Default task grid when database is not available -->
        {% for i in "1234" %}
        <div class="task-card">
            <h3>{{ forloop.counter }}.
                {% if forloop.counter == 1 %}SMCubes Core Creation
                {% elif forloop.counter == 2 %}SMCubes Transformation Rules
                {% elif forloop.counter == 3 %}Python Transformation Rules
                {% elif forloop.counter == 4 %}Full Execution
                {% endif %}
            </h3>
        </div>

        

        <div class="task-card">
            {% if forloop.counter < 1 %}
                <span class="operation-btn pending">Review</span>
            {% endif %}
        </div>

        <div class="task-card">
            {% if forloop.counter < 1 %}
                <span class="operation-btn pending">Compare</span>
            {% endif %}
        </div>
        {% endfor %}
    {% endif %}
</div>

<!-- Quick Actions -->
<div class="task-content">
    <h2>Quick Actions</h2>

    <div style="display: flex; gap: 20px; margin-top: 20px;">
        <div style="flex: 1;">
            <h3>Database Setup</h3>
            <p><strong>Step {% if migration_ready %}2{% else %}1{% endif %}:</strong> {% if migration_ready %}Ready to run database migrations{% else %}Download resources and prepare database{% endif %}</p>

            <form id="database-setup-form" method="post" action="{% url 'pybirdai:workflow_database_setup' %}">
                {% csrf_token %}
                <button type="button" id="database-setup-btn" class="btn operation-btn {% if migration_ready or setup_ready %} completed{% else %} running{% endif %}" style="width: 100%; margin-bottom: 10px;" onclick="startDatabaseSetup(); return false;">
                    Retrieve Artifacts
                </button>
            </form>
            <div id="database-setup-status" style="display: none; margin-top: 10px; margin-bottom: 10px; padding: 10px; border-radius: 5px;"></div>

            <form id="migration-form" method="post" action="{% url 'pybirdai:workflow_run_migrations' %}">
                {% csrf_token %}
                <button type="button" id="migration-btn" class="btn operation-btn {% if setup_ready %} completed {% else %}{% if migration_ready %} running{% else %} invalidated{% endif %}{% endif %}" style="width: 100%; margin-bottom: 10px;" onclick="startMigration(); return false;" {% if not migration_ready %}disabled{% endif %}>
                    Setup Database
                </button>
            </form>
            <div id="migration-status" style="display: none; margin-top: 10px; padding: 10px; border-radius: 5px;"></div>

            {% if migration_ready %}
                <p><small>Admin files were updated and server restarted. Click above to complete database setup.</small></p>
            {% endif %}
        </div>

        <div style="flex: 1;">
            <h3>Automode Execution</h3>
            <p>Run tasks automatically from Task 1 up to selected point</p>
            <form id="automode-form" method="post" action="{% url 'pybirdai:workflow_automode' %}">
                {% csrf_token %}
                <select name="target_task" class="form-control" style="margin-bottom: 10px;">
                    <option value="1">Task 1: SMCubes Core Creation</option>
                    <option value="2">Task 2: SMCubes Transformation Rules</option>
                    <option value="3">Task 3: Python Transformation Rules</option>
                    <option value="4" selected>Task 4: Full Execution</option>
                </select>
                <button type="submit" id="automode-btn" class="btn btn-primary" style="width: 100%; margin-bottom: 10px;">Run Automode (from Task 1)</button>
                <button type="button" id="clone-btn" class="btn btn-info" style="width: 100%; margin-bottom: 10px;" onclick="startCloneImport(); return false;">Clone (beta version)</button>
                <a href="{% url 'pybirdai:export_database_to_csv' %}" class="btn btn-secondary" style="width: 100%; display: block; text-align: center;">Create Review</a>
            </form>
            <div id="automode-status" style="display: none; margin-top: 10px; padding: 10px; border-radius: 5px;"></div>
            <div id="clone-status" style="display: none; margin-top: 10px; padding: 10px; border-radius: 5px;"></div>
        </div>

        <div style="flex: 1;">
            <h3>System Status</h3>
            <ul>
                <li>Database: {% if database_ready %}✅ Ready{% else %}❌ Not created{% endif %}</li>
                <li>Configuration: {% if config %}✅ Configured{% else %}❌ Not configured{% endif %}</li>
                {% if workflow_session %}
                    <li>Session ID: {{ workflow_session.session_id|slice:":8" }}...</li>
                {% else %}
                    <li>Session: ⏳ Waiting for database</li>
                {% endif %}
            </ul>

            <h4 style="margin-top: 20px;">Reset Session</h4>
            <button type="button" id="reset-session-partial-btn" class="btn btn-warning" style="width: 100%; margin-bottom: 10px;" onclick="resetSessionPartial(); return false;">
                Reset Tasks 1-4
            </button>
            <button type="button" id="reset-session-full-btn" class="btn btn-danger" style="width: 100%;" onclick="resetSessionFull(); return false;">
                Reset Everything
            </button>
            <div id="reset-session-status" style="display: none; margin-top: 10px; padding: 10px; border-radius: 5px;"></div>
        </div>
    </div>
</div>

<!-- Legend -->
<div class="task-content" style="margin-top: 20px;">
    <h3>Status Legend</h3>
    <div style="display: flex; gap: 20px; flex-wrap: wrap;">
        <span><span class="operation-btn" style="padding: 2px 8px;">⏳</span> Pending</span>
        <span><span class="operation-btn running" style="padding: 2px 8px;">🔄</span> Running</span>
        <span><span class="operation-btn completed" style="padding: 2px 8px;">✓</span> Completed</span>
        <span><span class="operation-btn failed" style="padding: 2px 8px;">✗</span> Failed</span>
        <span><span class="operation-btn paused" style="padding: 2px 8px;">⏸️</span> Paused</span>
        <span><span class="operation-btn invalidated" style="padding: 2px 8px;">🔄</span> Invalidated</span>
    </div>
</div>
{% endblock %}

{% block extra_css %}
{{ block.super }}
<style>
    /* Server Restart Overlay Styles */
    #server-restart-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.7);
        z-index: 9999;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    
    #server-restart-overlay .overlay-content {
        background: white;
        padding: 40px;
        border-radius: 10px;
        text-align: center;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
        max-width: 500px;
        width: 90%;
    }
    
    #server-restart-overlay h3 {
        margin-top: 20px;
        margin-bottom: 15px;
        color: #333;
    }
    
    #server-restart-overlay p {
        margin-bottom: 10px;
        color: #666;
    }
    
    #server-restart-overlay .overlay-timer {
        margin-top: 20px;
        font-size: 14px;
        color: #999;
    }
    
    #server-restart-overlay .spinner-border {
        width: 3rem;
        height: 3rem;
    }
</style>
{% endblock %}

{% block extra_js %}
<script>
// Simple database setup starter function (available immediately)
function startDatabaseSetup() {
    console.log('startDatabaseSetup() called directly!');

    const btn = document.getElementById('database-setup-btn');
    const statusDiv = document.getElementById('database-setup-status');

    if (!btn) {
        console.error('Database setup button not found!');
        alert('Error: Database setup button not found!');
        return;
    }

    if (!statusDiv) {
        console.error('Database setup status div not found!');
        alert('Error: Database setup status div not found!');
        return;
    }

    console.log('Button found:', btn);
    console.log('Status div found:', statusDiv);

    // Get CSRF token
    const databaseSetupForm = document.getElementById('database-setup-form');
    let csrfToken = '';

    if (databaseSetupForm) {
        const csrfInput = databaseSetupForm.querySelector('[name=csrfmiddlewaretoken]');
        if (csrfInput) {
            csrfToken = csrfInput.value;
            console.log('CSRF token found:', csrfToken.substring(0, 10) + '...');
        } else {
            console.error('CSRF input not found in form!');
        }
    } else {
        console.error('Database setup form not found!');
    }

    if (!csrfToken) {
        alert('Error: CSRF token not found! Please refresh the page.');
        return;
    }

    // Start the actual database setup
    doDatabaseSetup(btn, statusDiv, csrfToken);
}

function doDatabaseSetup(btn, statusDiv, csrfToken) {
    console.log('Starting actual database setup...');

    // Update UI
    btn.disabled = true;
    // btn.textContent = 'Setting up database...';
    statusDiv.style.display = 'block';
    statusDiv.style.background = '#e3f2fd';
    statusDiv.style.color = '#1976d2';
    statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">⏳</span>Starting database setup (Tasks 1-2)...';

    // Create form data
    const formData = new FormData();
    formData.append('csrfmiddlewaretoken', csrfToken);

    console.log('Sending AJAX request to /pybirdai/workflow/database-setup/');

    // Make AJAX request
    fetch('/pybirdai/workflow/database-setup/', {
        method: 'POST',
        body: formData,
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => {
        console.log('Database setup response received:', response.status, response.statusText);
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('Database setup response data:', data);
        if (data.success && data.status === 'started') {
            statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">⏳</span>Artefact retrieval started in background. Polling for status...';
            pollDatabaseSetupStatus(statusDiv, btn);
        } else {
            statusDiv.style.background = '#f8d7da';
            statusDiv.style.color = '#721c24';
            statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">❌</span>Failed to start: ' + (data.message || 'Unknown error');
            btn.disabled = false;
            btn.textContent = 'Retireive Artifacts';
        }
    })
    .catch(error => {
        console.error('Database setup error:', error);
        statusDiv.style.background = '#f8d7da';
        statusDiv.style.color = '#721c24';
        statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">❌</span>Error: ' + error.message;
        btn.disabled = false;
        btn.textContent = 'Retireive Artifacts';
    });
}

// Database setup form AJAX handler (still needed for DOM ready handler)
document.addEventListener('DOMContentLoaded', function() {

    // Automode form AJAX handler
    const automodeForm = document.getElementById('automode-form');
    const automodeBtn = document.getElementById('automode-btn');
    const automodeStatus = document.getElementById('automode-status');

    if (automodeForm && automodeBtn && automodeStatus) {
        automodeForm.addEventListener('submit', function(e) {
            e.preventDefault();

            const targetTask = automodeForm.querySelector('[name="target_task"]').value;

            // Disable button and show loading
            automodeBtn.disabled = true;
            automodeBtn.textContent = `Running automode to Task ${targetTask}...`;
            automodeStatus.style.display = 'block';
            automodeStatus.style.background = '#e3f2fd';
            automodeStatus.style.color = '#1976d2';
            automodeStatus.innerHTML = `<span style="display: inline-block; margin-right: 8px;">⏳</span>Running automode from Task 1 to Task ${targetTask}...`;

            // Get form data
            const formData = new FormData(automodeForm);

            // Make AJAX request
            fetch('/pybirdai/workflow/automode/', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success && data.status === 'started') {
                    automodeStatus.style.background = '#e3f2fd';
                    automodeStatus.style.color = '#1976d2';
                    automodeStatus.innerHTML = '<span style="display: inline-block; margin-right: 8px;">⏳</span>Automode started in background. Polling for status...';

                    // Start polling for status
                    pollAutomodeStatus(automodeStatus, automodeBtn, targetTask);
                } else {
                    automodeStatus.style.background = '#f8d7da';
                    automodeStatus.style.color = '#721c24';
                    let errorMsg = 'Automode failed to start';
                    if (data.message) {
                        errorMsg = data.message;
                    } else if (data.errors && data.errors.length > 0) {
                        errorMsg += ': ' + data.errors.map(e => `Task ${e.task}: ${e.error}`).join(', ');
                    }
                    automodeStatus.innerHTML = '<span style="display: inline-block; margin-right: 8px;">❌</span>' + errorMsg;

                    automodeBtn.disabled = false;
                    automodeBtn.textContent = 'Run Automode (from Task 1)';
                }
            })
            .catch(error => {
                console.error('Automode error:', error);
                automodeStatus.style.background = '#f8d7da';
                automodeStatus.style.color = '#721c24';
                automodeStatus.innerHTML = '<span style="display: inline-block; margin-right: 8px;">❌</span>Error: ' + error.message;

                automodeBtn.disabled = false;
                automodeBtn.textContent = 'Run Automode (from Task 1)';
            });
        });
    }
});

// Simple migration starter function (available immediately)
function startMigration() {
    console.log('startMigration() called directly!');


    const btn = document.getElementById('migration-btn');
    const statusDiv = document.getElementById('migration-status');

    if (!btn) {
        console.error('Migration button not found!');
        alert('Error: Migration button not found!');
        return;
    }

    if (!statusDiv) {
        console.error('Migration status div not found!');
        alert('Error: Migration status div not found!');
        return;
    }

    console.log('Button found:', btn);
    console.log('Status div found:', statusDiv);

    // Get CSRF token
    const migrationForm = document.getElementById('migration-form');
    let csrfToken = '';

    if (migrationForm) {
        const csrfInput = migrationForm.querySelector('[name=csrfmiddlewaretoken]');
        if (csrfInput) {
            csrfToken = csrfInput.value;
            console.log('CSRF token found:', csrfToken.substring(0, 10) + '...');
        } else {
            console.error('CSRF input not found in form!');
        }
    } else {
        console.error('Migration form not found!');
    }

    if (!csrfToken) {
        alert('Error: CSRF token not found! Please refresh the page.');
        return;
    }

    // Start the actual migration
    doMigration(btn, statusDiv, csrfToken);
}

function doMigration(btn, statusDiv, csrfToken) {
    console.log('Starting actual migration...');

    // Update UI
    btn.disabled = true;
    statusDiv.style.display = 'block';
    statusDiv.style.background = '#e3f2fd';
    statusDiv.style.color = '#1976d2';
    statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">⏳</span>Starting database setup...';

    // Create form data
    const formData = new FormData();
    formData.append('csrfmiddlewaretoken', csrfToken);

    console.log('Sending AJAX request to /pybirdai/workflow/run-migrations/');

    // Make AJAX request
    fetch('/pybirdai/workflow/run-migrations/', {
        method: 'POST',
        body: formData,
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => {
        console.log('Migration response received:', response.status, response.statusText);
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('Migration response data:', data);
        if (data.success && data.status === 'started') {
            statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">⏳</span>Database setup started in background. Polling for status...';
            pollMigrationStatus(statusDiv, btn);
        } else {
            statusDiv.style.background = '#f8d7da';
            statusDiv.style.color = '#721c24';
            statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">❌</span>Failed to start: ' + (data.message || 'Unknown error');
            btn.disabled = false;
        }
    })
    .catch(error => {
        console.error('Migration error:', error);
        statusDiv.style.background = '#f8d7da';
        statusDiv.style.color = '#721c24';
        statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">❌</span>Error: ' + error.message;
        btn.disabled = false;
    });
}

// Function to poll database setup status
function pollDatabaseSetupStatus(statusDiv, btn) {
    const pollInterval = 2000; // Poll every 2 seconds
    let pollCount = 0;
    const maxPolls = 300; // Maximum 10 minutes (300 * 2 seconds)

    function checkStatus() {
        fetch('/pybirdai/workflow/database-setup-status/', {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            console.log('Database setup status:', data); // Debug log

            if (data.success && data.database_setup_status) {
                const status = data.database_setup_status;

                if (status.running) {
                    // Still running - update status message
                    const elapsedTime = Math.round(status.elapsed_time || 0);
                    let message = `<span style="display: inline-block; margin-right: 8px;">⏳</span>${status.message || 'Artefact Retrieval Running...'} (${elapsedTime}s elapsed)`;
                    if (status.current_task) {
                        message += ` - Processing`;
                    }
                    statusDiv.innerHTML = message;

                    // Continue polling
                    pollCount++;
                    if (pollCount < maxPolls) {
                        setTimeout(checkStatus, pollInterval);
                    } else {
                        // Timeout
                        statusDiv.style.background = '#fff3cd';
                        statusDiv.style.color = '#856404';
                        statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">⚠️</span>Database setup is taking longer than expected. Please check server logs.';
                        btn.disabled = false;
                    }
                } else if (status.completed) {
                    // Setup completed
                    console.log('Database setup completed! Status object:', status);

                    if (status.success) {
                        statusDiv.style.background = '#d4edda';
                        statusDiv.style.color = '#155724';
                        const elapsedTime = Math.round(status.elapsed_time || 0);
                        let message = `<span style="display: inline-block; margin-right: 8px;">✅</span>${status.message || 'Database setup completed successfully'} (${elapsedTime}s)`;

                        if (status.completed_tasks && status.completed_tasks.length > 0) {
                            message += `<br>Completed: ${status.completed_tasks.join(', ')}`;
                        }

                        // Check for server restart requirement with comprehensive logic
                        const serverRestartRequired = status.server_restart_required === true;
                        const messageIndicatesRestart = status.message && (
                            status.message.includes('restart required') ||
                            status.message.includes('Server restart required') ||
                            status.message.includes('server restart')
                        );

                        console.log('Restart check:', {
                            serverRestartRequired,
                            messageIndicatesRestart,
                            message: status.message,
                            hasRestartInfo: !!status.restart_info,
                            hasEstimatedTime: !!status.estimated_restart_time
                        });

                        if (serverRestartRequired || messageIndicatesRestart) {
                            console.log('🔄 Database setup completed - server restart required detected!');
                            message += '<br><strong>🔄 Server restart in progress...</strong>';
                            if (status.restart_info) {
                                message += `<br><small>${status.restart_info}</small>`;
                            } else if (status.estimated_restart_time) {
                                message += `<br><small>${status.estimated_restart_time}</small>`;
                            }
                            statusDiv.innerHTML = message;

                            // Handle server restart scenario
                            handleServerRestart(statusDiv, btn);
                        } else {
                            console.log('✅ Database setup completed - no server restart required');
                            statusDiv.innerHTML = message;

                            // Regular refresh for non-restart scenarios
                            setTimeout(() => {
                                console.log('Refreshing page after successful setup (no restart)');
                                location.reload();
                            }, 3000);
                        }
                    } else {
                        statusDiv.style.background = '#f8d7da';
                        statusDiv.style.color = '#721c24';
                        statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">❌</span>Database setup failed: ' + (status.error || status.message || 'Unknown error');

                        btn.disabled = false;
                    }
                }
            } else {
                // Error getting status
                statusDiv.style.background = '#f8d7da';
                statusDiv.style.color = '#721c24';
                statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">❌</span>Error checking database setup status';

                btn.disabled = false;
            }
        })
        .catch(error => {
            console.error('Database setup status polling error:', error);

            // Check if this might be a server restart scenario (connection lost during polling)
            if (error.name === 'TypeError' || error.message.includes('Failed to fetch') || error.message.includes('NetworkError') || error.name === 'TimeoutError') {
                console.log('🔄 Connection lost during database setup polling - likely server restart!');
                // Possible server restart - show appropriate message
                statusDiv.style.background = '#e3f2fd';
                statusDiv.style.color = '#1976d2';
                statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">🔄</span>✅ Database setup completed! Connection lost - server is restarting...';

                // Switch to restart detection mode
                handleServerRestart(statusDiv, btn);
            } else {
                // Other error - show error message
                statusDiv.style.background = '#f8d7da';
                statusDiv.style.color = '#721c24';
                statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">❌</span>Error checking database setup status: ' + error.message;

                btn.disabled = false;
            }
        }).catch(error => {
          console.error('Database setup status polling error:', error);

          // Refresh page on error to reset state
          setTimeout(() => {
              console.log('Refreshing page due to database setup polling error');
              location.reload();
          }, 2000);
        }
        );
    }

    // Start polling
    setTimeout(checkStatus, pollInterval);
}

// Function to poll migration status
function pollMigrationStatus(statusDiv, btn) {
    const pollInterval = 2000; // Poll every 2 seconds
    let pollCount = 0;
    const maxPolls = 450; // Maximum 15 minutes (300 * 2 seconds)

    function checkStatus() {
        fetch('/pybirdai/workflow/migration-status/', {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            console.log('Migration status:', data); // Debug log

            if (data.success && data.migration_status) {
                const status = data.migration_status;

                if (status.running) {
                    // Still running - update status message
                    const elapsedTime = Math.round(status.elapsed_time || 0);
                    statusDiv.innerHTML = `<span style="display: inline-block; margin-right: 8px;">⏳</span>Database setup running in background... (${elapsedTime}s elapsed)`;

                    // Continue polling
                    pollCount++;
                    if (pollCount < maxPolls) {
                        setTimeout(checkStatus, pollInterval);
                    } else {
                        // Timeout
                        statusDiv.style.background = '#fff3cd';
                        statusDiv.style.color = '#856404';
                        statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">⚠️</span>Database setup is taking longer than expected. Please check server logs.';
                        btn.disabled = false;
                    }
                } else if (status.completed) {
                    // Migration completed
                    console.log('Migration completed! Status object:', status);

                    if (status.success) {
                        statusDiv.style.background = '#d4edda';
                        statusDiv.style.color = '#155724';
                        const elapsedTime = Math.round(status.elapsed_time || 0);
                        let message = `<span style="display: inline-block; margin-right: 8px;">✅</span>${status.message || 'Database migrations completed successfully'} (${elapsedTime}s)`;

                        // Check for server restart requirement
                        const serverRestartRequired = status.server_restart_required === true;
                        const messageIndicatesRestart = status.message && (
                            status.message.includes('restart required') ||
                            status.message.includes('Server restart required') ||
                            status.message.includes('server restart')
                        );

                        console.log('Migration restart check:', {
                            serverRestartRequired,
                            messageIndicatesRestart,
                            message: status.message
                        });

                        if (serverRestartRequired || messageIndicatesRestart) {
                            console.log('🔄 Database setup completed - server restart required detected!');
                            message += '<br><strong>🔄 Server restart in progress...</strong>';
                            if (status.restart_info) {
                                message += `<br><small>${status.restart_info}</small>`;
                            } else if (status.estimated_restart_time) {
                                message += `<br><small>${status.estimated_restart_time}</small>`;
                            }
                            statusDiv.innerHTML = message;

                            // Handle server restart scenario
                            handleServerRestart(statusDiv, btn);
                        } else {
                            console.log('✅ Database setup completed - no server restart required');
                            statusDiv.innerHTML = message + '<br>The database is now ready for use.';

                            // Regular refresh for non-restart scenarios
                            setTimeout(() => {
                                console.log('Refreshing page after successful migration (no restart)');
                                location.reload();
                            }, 3000);
                        }
                    } else {
                        statusDiv.style.background = '#f8d7da';
                        statusDiv.style.color = '#721c24';
                        statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">❌</span>Migration failed: ' + (status.error || status.message || 'Unknown error');

                        btn.disabled = false;
                    }
                }
            } else {
                // Error getting status
                statusDiv.style.background = '#f8d7da';
                statusDiv.style.color = '#721c24';
                statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">❌</span>Error checking migration status';

                btn.disabled = false;
            }
        })
        .catch(error => {
            console.error('Migration status polling error:', error);

            // Check if this might be a server restart scenario (connection lost during polling)
            if (error.name === 'TypeError' || error.message.includes('Failed to fetch') || error.message.includes('NetworkError') || error.name === 'TimeoutError') {
                console.log('🔄 Connection lost during migration polling - likely server restart!');
                // Possible server restart - show appropriate message
                statusDiv.style.background = '#e3f2fd';
                statusDiv.style.color = '#1976d2';
                statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">🔄</span>✅ Database setup completed! Connection lost - server is restarting...';

                // Switch to restart detection mode
                handleServerRestart(statusDiv, btn);
            } else {
                // Other error - refresh page to reset state
                setTimeout(() => {
                    console.log('Refreshing page due to migration polling error');
                    location.reload();
                }, 2000);
            }
        });
    }

    // Start polling
    setTimeout(checkStatus, pollInterval);
}

// Function to poll automode status
function pollAutomodeStatus(statusDiv, btn, targetTask) {
    const pollInterval = 2000; // Poll every 2 seconds
    let pollCount = 0;
    const maxPolls = 600; // Maximum 20 minutes (600 * 2 seconds) for automode

    function checkStatus() {
        fetch('/pybirdai/workflow/automode-status/', {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            console.log('Automode status:', data); // Debug log

            if (data.success && data.automode_status) {
                const status = data.automode_status;

                if (status.running) {
                    // Still running - update status message
                    const elapsedTime = Math.round(status.elapsed_time || 0);
                    let message = `<span style="display: inline-block; margin-right: 8px;">⏳</span>${status.message || 'Automode running...'} (${elapsedTime}s elapsed)`;

                    if (status.current_task) {
                        message += ` - Currently on Task ${status.current_task}`;
                        if (status.target_task) {
                            message += ` of ${status.target_task}`;
                        }
                    }

                    if (status.completed_tasks && status.completed_tasks.length > 0) {
                        message += `<br>Completed: ${status.completed_tasks.join(', ')}`;
                    }

                    statusDiv.innerHTML = message;

                    // Continue polling
                    pollCount++;
                    if (pollCount < maxPolls) {
                        setTimeout(checkStatus, pollInterval);
                    } else {
                        // Timeout
                        statusDiv.style.background = '#fff3cd';
                        statusDiv.style.color = '#856404';
                        statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">⚠️</span>Automode is taking longer than expected. Please check server logs.';
                        btn.disabled = false;
                        btn.textContent = 'Run Automode (from Task 1)';
                    }
                } else if (status.completed) {
                    // Automode completed
                    if (status.success) {
                        statusDiv.style.background = '#d4edda';
                        statusDiv.style.color = '#155724';
                        const elapsedTime = Math.round(status.elapsed_time || 0);
                        statusDiv.innerHTML = `<span style="display: inline-block; margin-right: 8px;">✅</span>${status.message || 'Automode completed successfully'} (${elapsedTime}s)`;

                        // Refresh page after success to show updated task status
                        setTimeout(() => {
                            location.reload();
                        }, 3000);
                    } else {
                        statusDiv.style.background = '#f8d7da';
                        statusDiv.style.color = '#721c24';
                        let errorMsg = status.message || 'Automode failed';

                        if (status.task_errors && status.task_errors.length > 0) {
                            errorMsg += '<br>Errors: ' + status.task_errors.map(e => `Task ${e.task}: ${e.error}`).join('<br>');
                        }

                        statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">❌</span>' + errorMsg;

                        btn.disabled = false;
                        btn.textContent = 'Run Automode (from Task 1)';
                    }
                }
            } else {
                // Error getting status
                statusDiv.style.background = '#f8d7da';
                statusDiv.style.color = '#721c24';
                statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">❌</span>Error checking automode status';

                btn.disabled = false;
                btn.textContent = 'Run Automode (from Task 1)';
            }
        }).catch(error => {
          console.error('Database setup status polling error:', error);

          // Refresh page on error to reset state
          setTimeout(() => {
              console.log('Refreshing page due to database setup polling error');
              location.reload();
          }, 2000);
        }
        );
    }

    // Start polling
    setTimeout(checkStatus, pollInterval);
}

// Function to handle server restart detection and UI refresh
function handleServerRestart(statusDiv, btn) {
    console.log('handleServerRestart() called - starting server restart detection');

    // Show the overlay
    const overlay = document.getElementById('server-restart-overlay');
    if (overlay) {
        overlay.style.display = 'flex';
    }

    // Update UI immediately to show restart is happening
    statusDiv.style.background = '#e3f2fd';
    statusDiv.style.color = '#1976d2';
    statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">🔄</span>✅ Database setup completed! Server is restarting due to file changes...';

    // Disable button immediately to prevent double-clicks during restart
    btn.disabled = true;
    btn.textContent = 'Server Restarting...';

    const restartPollInterval = 5000; // Poll every 5 seconds as requested
    let restartPollCount = 0;
    const maxRestartPolls = 60; // Maximum 5 minutes (60 * 5 seconds)
    let serverWentDown = false;
    let timerInterval = null;

    // Start timer for overlay
    let elapsedSeconds = 0;
    timerInterval = setInterval(() => {
        elapsedSeconds++;
        const timerElement = document.getElementById('overlay-timer-seconds');
        if (timerElement) {
            timerElement.textContent = elapsedSeconds;
        }
    }, 1000);

    function updateRestartMessage(seconds) {
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = seconds % 60;
        const timeStr = minutes > 0 ? `${minutes}m ${remainingSeconds}s` : `${seconds}s`;

        if (!serverWentDown) {
            statusDiv.innerHTML = `<span style="display: inline-block; margin-right: 8px;">🔄</span>✅ Database setup completed! Waiting for server restart... (${timeStr})<br><small>After restart, button will change to "Setup Database"</small>`;
        } else {
            statusDiv.innerHTML = `<span style="display: inline-block; margin-right: 8px;">🔄</span>Server is restarting... (${timeStr})<br><small>Page will refresh to show "Setup Database" button</small>`;
        }
    }

    function checkServerStatus() {
        restartPollCount++;
        const pollElapsedSeconds = Math.floor(restartPollCount * 5); // Updated for 5s polling interval

        // Update message with elapsed time
        updateRestartMessage(pollElapsedSeconds);

        // Try to ping the server
        fetch('/pybirdai/workflow/', {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            },
            // Add timeout to detect connection issues faster
            signal: AbortSignal.timeout(4000) // 4 second timeout
        })
        .then(response => {
            if (response.ok) {
                // Server is back online
                console.log('Server restart completed - server is back online');
                
                // Clear timer
                if (timerInterval) {
                    clearInterval(timerInterval);
                }
                
                // Hide overlay
                if (overlay) {
                    overlay.style.display = 'none';
                }
                
                statusDiv.style.background = '#d4edda';
                statusDiv.style.color = '#155724';
                statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">✅</span>🎉 Server restart completed! Refreshing page to show "Setup Database" button...';

                // Disable the database setup button immediately to prevent double-clicks
                btn.disabled = true;
                btn.textContent = 'Refreshing...';

                // Refresh page after delay to ensure server is fully ready and marker file is detected
                setTimeout(() => {
                    console.log('Refreshing page after server restart to show migration button');
                    location.reload();
                }, 2000); // 2 second delay to ensure server is fully ready
            } else {
                // Server still restarting or responding with non-200 status
                if (restartPollCount < maxRestartPolls) {
                    setTimeout(checkServerStatus, restartPollInterval);
                } else {
                    // Timeout
                    if (timerInterval) {
                        clearInterval(timerInterval);
                    }
                    if (overlay) {
                        overlay.style.display = 'none';
                    }
                    statusDiv.style.background = '#fff3cd';
                    statusDiv.style.color = '#856404';
                    statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">⚠️</span>Server restart is taking longer than expected. Please refresh the page manually.';
                    btn.disabled = false;
                    btn.textContent = 'Retrieve Artifacts and Setup Database';
                }
            }
        })
        .catch(error => {
            // Server is likely still restarting (connection refused/network error)
            if (!serverWentDown) {
                serverWentDown = true;
                console.log('Server restart detected - connection lost:', error.name);
            }

            if (restartPollCount < maxRestartPolls) {
                setTimeout(checkServerStatus, restartPollInterval);
            } else {
                // Timeout
                if (timerInterval) {
                    clearInterval(timerInterval);
                }
                if (overlay) {
                    overlay.style.display = 'none';
                }
                statusDiv.style.background = '#fff3cd';
                statusDiv.style.color = '#856404';
                statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">⚠️</span>Server restart is taking longer than expected. Please refresh the page manually or check the server console.';
                btn.disabled = false;
                btn.textContent = 'Retrieve Artifacts and Setup Database';
            }
        });
    }

    // Start checking server status after initial delay
    console.log('Starting server restart detection polling...');
    setTimeout(checkServerStatus, 10000); // Check after 10 seconds as requested

    // Fallback: force page refresh after 5 minutes if restart detection fails
    setTimeout(() => {
        if (btn.disabled && btn.textContent.includes('Restarting')) {
            console.log('Fallback: Force refreshing page after restart timeout');
            if (timerInterval) {
                clearInterval(timerInterval);
            }
            if (overlay) {
                overlay.style.display = 'none';
            }
            statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">🔄</span>Restart taking longer than expected - refreshing page...';
            location.reload();
        }
    }, 300000); // 5 minutes fallback
}

// Clone import function
function startCloneImport() {
    console.log('startCloneImport() called');

    const btn = document.getElementById('clone-btn');
    const statusDiv = document.getElementById('clone-status');

    if (!btn || !statusDiv) {
        console.error('Clone button or status div not found!');
        alert('Error: UI elements not found!');
        return;
    }

    // Get CSRF token
    const automodeForm = document.getElementById('automode-form');
    let csrfToken = '';

    if (automodeForm) {
        const csrfInput = automodeForm.querySelector('[name=csrfmiddlewaretoken]');
        if (csrfInput) {
            csrfToken = csrfInput.value;
        }
    }

    if (!csrfToken) {
        alert('Error: CSRF token not found! Please refresh the page.');
        return;
    }

    // Update UI
    btn.disabled = true;
    btn.textContent = 'Importing CSVs...';
    statusDiv.style.display = 'block';
    statusDiv.style.background = '#e3f2fd';
    statusDiv.style.color = '#1976d2';
    statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">⏳</span>Cloning Previous smcubes database setup from github';

    // Create form data
    const formData = new FormData();
    formData.append('csrfmiddlewaretoken', csrfToken);

    // Make AJAX request to clone endpoint
    fetch('/pybirdai/workflow/clone-import/', {
        method: 'POST',
        body: formData,
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => {
        console.log('Clone import response received:', response.status);
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('Clone import response data:', data);
        if (data.success) {
            statusDiv.style.background = '#d4edda';
            statusDiv.style.color = '#155724';
            let message = `<span style="display: inline-block; margin-right: 8px;">✅</span>${data.message}`;
            if (data.details) {
                message += `<br><small>${data.details}</small>`;
            }
            statusDiv.innerHTML = message;

            // Re-enable button after success
            setTimeout(() => {
                btn.disabled = false;
                btn.textContent = 'Clone (beta version)';
                // Optionally refresh to show updated data
                if (data.refresh_recommended) {
                    setTimeout(() => {
                        location.reload();
                    }, 2000);
                }
            }, 3000);
        } else {
            statusDiv.style.background = '#f8d7da';
            statusDiv.style.color = '#721c24';
            statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">❌</span>Clone import failed: ' + (data.error || data.message || 'Unknown error');

            btn.disabled = false;
            btn.textContent = 'Clone (beta version)';
        }
    })
    .catch(error => {
        console.error('Clone import error:', error);
        statusDiv.style.background = '#f8d7da';
        statusDiv.style.color = '#721c24';
        statusDiv.innerHTML = '<span style="display: inline-block; margin-right: 8px;">❌</span>Error: ' + error.message;

        btn.disabled = false;
        btn.textContent = 'Clone (beta version)';
    });
}

// Reset session functions
function resetSessionPartial() {
    if (!confirm('Are you sure you want to reset tasks 1-4? This will clear all progress from Task 1 onwards while keeping the database setup (Tasks 1-2) intact.')) {
        return;
    }

    doResetSession('partial');
}

function resetSessionFull() {
    if (!confirm('Are you sure you want to reset the entire workflow session? This will clear ALL progress including database setup and return to the beginning.')) {
        return;
    }

    doResetSession('full');
}

function doResetSession(type) {
    const isPartial = type === 'partial';
    const btnId = isPartial ? 'reset-session-partial-btn' : 'reset-session-full-btn';
    const url = isPartial ? '/pybirdai/workflow/reset-session-partial/' : '/pybirdai/workflow/reset-session-full/';

    const btn = document.getElementById(btnId);
    const statusDiv = document.getElementById('reset-session-status');

    if (!btn || !statusDiv) {
        console.error('Reset session button or status div not found!');
        alert('Error: UI elements not found!');
        return;
    }

    // Get CSRF token
    const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;

    if (!csrfToken) {
        alert('Error: CSRF token not found! Please refresh the page.');
        return;
    }

    // Update UI
    btn.disabled = true;
    btn.textContent = `Resetting ${isPartial ? 'Tasks 1-4' : 'All Tasks'}...`;
    statusDiv.style.display = 'block';
    statusDiv.style.background = '#e3f2fd';
    statusDiv.style.color = '#1976d2';
    statusDiv.innerHTML = `<span style="display: inline-block; margin-right: 8px;">⏳</span>Resetting ${isPartial ? 'tasks 1-4' : 'entire workflow session'}...`;

    // Create form data
    const formData = new FormData();
    formData.append('csrfmiddlewaretoken', csrfToken);

    // Make AJAX request
    fetch(url, {
        method: 'POST',
        body: formData,
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => {
        console.log('Reset session response received:', response.status);
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('Reset session response data:', data);
        if (data.success) {
            statusDiv.style.background = '#d4edda';
            statusDiv.style.color = '#155724';
            let message = `<span style="display: inline-block; margin-right: 8px;">✅</span>${data.message}`;

            if (data.details) {
                const details = data.details;
                let detailsText = '';
                if (details.removed_markers && details.removed_markers.length > 0) {
                    detailsText += `<br><small>Removed markers: ${details.removed_markers.join(', ')}</small>`;
                }
                if (details.removed_directories && details.removed_directories.length > 0) {
                    detailsText += `<br><small>Cleaned directories: ${details.removed_directories.length} items</small>`;
                }
                if (details.deleted_executions) {
                    detailsText += `<br><small>Deleted executions: ${details.deleted_executions}</small>`;
                }
                message += detailsText;
            }

            statusDiv.innerHTML = message;

            // Re-enable button and refresh page after delay
            setTimeout(() => {
                btn.disabled = false;
                btn.textContent = isPartial ? 'Reset Tasks 1-4' : 'Reset Everything';
                statusDiv.innerHTML += '<br><small>Refreshing page to reflect changes...</small>';

                // Refresh page to show updated state
                setTimeout(() => {
                    location.reload();
                }, 2000);
            }, 3000);
        } else {
            statusDiv.style.background = '#f8d7da';
            statusDiv.style.color = '#721c24';
            statusDiv.innerHTML = `<span style="display: inline-block; margin-right: 8px;">❌</span>Reset failed: ${data.message || data.error || 'Unknown error'}`;

            btn.disabled = false;
            btn.textContent = isPartial ? 'Reset Tasks 1-4' : 'Reset Everything';
        }
    })
    .catch(error => {
        console.error('Reset session error:', error);
        statusDiv.style.background = '#f8d7da';
        statusDiv.style.color = '#721c24';
        statusDiv.innerHTML = `<span style="display: inline-block; margin-right: 8px;">❌</span>Error: ${error.message}`;

        btn.disabled = false;
        btn.textContent = isPartial ? 'Reset Tasks 1-4' : 'Reset Everything';
    });
}
</script>

{% endblock %}
